package com.zt.springcloud.service.Impl;

import cloud.zt.springboot.exception.Exp.ServiceException;
import cloud.zt.springboot.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.zt.springcloud.entity.Cart;
import com.zt.springcloud.entity.vo.CartVo;
import com.zt.springcloud.mapper.ProductMapper;
import com.zt.springcloud.mapper.ShopCartMapper;
import com.zt.springcloud.mapper.UserMapper;
import com.zt.springcloud.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author RedReins
 * @version 1.0
 * @description: TODO
 * @date 2021/9/19 11:11
 */

@Service
public class ShopCartServiceImpl implements ShopCartService {
    @Autowired
    private ShopCartMapper shopCartMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductMapper productMapper;
    @Override
    public int insertCart(Cart cart) {

        /*获取用户id*/
        Long userid = userMapper.selectUserByUserName(cart.getUsername()).getId();
        cart.setUserId(userid);
        long itemId = cart.getItemId();
        Boolean item = productMapper.findItem(itemId);
        /*如果数据中找到商品*/
        if(item){
            return shopCartMapper.insertCart(cart);
        }else{
            return 0;
        }
    }

    @Override
    public List<CartVo> getCartList(Long id) {
        List<CartVo> cartList = shopCartMapper.getCartList(id);
        for(CartVo v:cartList){
            System.out.println(v.getImageUrl());
        }
        return cartList;
    }

    @Override
    public Integer addShopCartAmount(Integer itemid) {
        return shopCartMapper.addShopCartAmount(itemid);
    }

    @Override
    public Integer minusShopCartAmount(Integer itemid) {
        return shopCartMapper.minusShopCartAmount(itemid);
    }

    @Override
    public List<CartVo> findItemsByIds(String itemIds) throws Exception {
        System.out.println(itemIds);
        List<CartVo> products = new ArrayList<>();
        try{
            /*类型转换*/
            List<Integer> list = JSON.parseObject(itemIds,List.class);
            /*实例化一个空数组*/
            /*循环查询购物车中的商品*/
            list.stream().forEach(itemid -> {
                CartVo itemInfo = shopCartMapper.findItemById(itemid);
                if(!StringUtils.isNull(itemInfo)){
                    products.add(itemInfo);
                }
            });
        }catch (Exception e){
            throw new ServiceException("类型转换异常"+e);
        }

        return products;
    }
}
